package cn.tinlan.shopcoin.app.login;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import butterknife.BindView;
import cn.tinlan.shopcoin.MainActivity;
import cn.tinlan.shopcoin.R;

import cn.tinlan.shopcoin.Utils.CacheManager;
import cn.tinlan.shopcoin.Utils.ConvertUtil;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;

/**
 * Created by Mortimer on 2018/11/28. 10:43
 * 佛祖🙏，永无bug。
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.login_account)
    EditText login_account;
    @BindView(R.id.login_password)
    EditText login_password;
    @BindView(R.id.login_forword)
    TextView login_forword;
    @BindView(R.id.login_register)
    TextView login_register;
    @BindView(R.id.login_btn)
    Button login_btn;

    private int index = 0;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }


    @Override
    public void initView() {
        super.initView();
        drawableDefaultBar();
        initLoginView();
    }

    private void initLoginView() {

        index = getIntent().getIntExtra("index",0);

        login_forword.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        login_register.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login_register:
                toRegister();
                break;
            case R.id.login_forword:
                toResettingPWD();
                break;
            case R.id.login_btn:
                loginBtnClick();
                break;
        }
    }


    private void toRegister() {
        startActivityForResult(new Intent(LoginActivity.this, RegisterActivity.class),1043);

    }

    private void toResettingPWD() {
        startActivity(new Intent(LoginActivity.this,forgetPasswordActivity.class));
    }

    private void loginBtnClick(){

        String mobile = login_account.getText().toString().trim();

        if (mobile.isEmpty() || mobile.length() != 11) {
            ToastUtils.show("请输入正确的手机号");
            return;
        }
//        if (login_account.getText().toString().trim().length() != 0 && login_password.getText().toString().trim().length() != 0){


            String pwd = login_password.getText().toString().trim();
            EasyHttp.post(Constants.LoginApp)
                    .params("mobile",mobile)
                    .params("pwd",pwd)
                    .execute(new CallBackProxy<CustomApiResult<UserModel>, UserModel>(new SimpleCallBack<UserModel>() {
                        @Override
                        public void onError(ApiException e) {

//                            if (e.getCode() == 2) {
//                                Log.d("code2",e.getMessage()+"1111111"+e.getDisplayMessage());
//                                ToastUtils.show(e.getMessage());
//                            }
//                            try {
//                                e.getCode();
//                                e.getDisplayMessage()
//                            }catch (Exception e){
//                                e.printStackTrace();
//                            }
//                            if (!e.getDisplayMessage().isEmpty()) {
//                                ToastUtils.show(e.getDisplayMessage());
//                            }else {
                                ToastUtils.show("登陆失败");
//                            }


                        }
                        @Override
                        public void onSuccess(UserModel userModel) {

//                            Log.d("code2",userModel.getData());

                            if (!userModel.getId().isEmpty()) {
                                if (SPUtils.saveUserBean(LoginActivity.this,userModel)) {
                                    UserModel tempUserModel1 = SPUtils.getUserBean(LoginActivity.this);
                                }
                                SPUtils.putParam(LoginActivity.this,"isLogin",true);
                                SPUtils.putParam(LoginActivity.this,"userID",userModel.getId());
                                if (index != 0) {
                                    Intent intent = new Intent();
                                    intent.putExtra("resultIndex",index);
                                    setResult(1851,intent);
                                    finish();
                                }else {
                                    finish();
                                }

                            }

//                            if (CacheManager.saveUserModel(LoginActivity.this,userModel)){
//                                UserModel tempUserModel1 = CacheManager.readUserModel(LoginActivity.this);
//                                Log.d("111111",tempUserModel1.toString());
//                            }
                        }
                    }) {
                    });

//        }else {
//            ToastUtils.show("输入有误,请重新输入");
//        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1022) {
            String mobile = data.getStringExtra("mobile");
            if (!mobile.isEmpty()) {
                login_account.setText(mobile);
            }
        }



    }





    //实现点击屏幕收起键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ev.getAction()==MotionEvent.ACTION_DOWN){
            View v=getCurrentFocus();
            boolean  hideInputResult =isShouldHideInput(v,ev);
            Log.v("hideInputResult","zzz-->>"+hideInputResult);
            if(hideInputResult){
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) LoginActivity.this
                        .getSystemService(Activity.INPUT_METHOD_SERVICE);
                if(v != null){
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            //之前一直不成功的原因是,getX获取的是相对父视图的坐标,getRawX获取的才是相对屏幕原点的坐标！！！
//            Log.v("leftTop[]","zz--left:"+left+"--top:"+top+"--bottom:"+bottom+"--right:"+right);
//            Log.v("event","zz--getX():"+event.getRawX()+"--getY():"+event.getRawY());
            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


}
